package sim32;
/**
 * 
 */
import java.io.*;
import java.util.Scanner;
import java.util.TreeMap;

/**
 * The instruction memory class. Loads the program from the file and creates instructions.
 * @author Piotr
 *
 */
public class IMemory {
	TreeMap<Integer, String[]> imem;
	int byteCount;
	
	/**
	 * Creates a new IMemory and fills it using the program file.
	 * @param program	file containing the program.
	 * @throws FileNotFoundException 
	 */
	IMemory(File program) throws FileNotFoundException {
		Scanner scin = new Scanner(program);
		Scanner scline;
		String line;
		imem = new TreeMap<Integer, String[]>();
		int address;
		String[] strings;
		while (scin.hasNext()) {			// Add some safety checks here
			line = scin.nextLine();
			scline = new Scanner(line);
			strings = new String[2];
			address = scline.nextInt(10);	// Radix 10 addresses
			strings[0] = scline.next();
			strings[1] = scline.nextLine().trim();
			if (!imem.containsKey(address)) {
				imem.put(address, strings);
			} else {
				System.out.println("Error, repeat addresses in program file: " + address);
				
			}
		}
		byteCount = 0;
		
	}
	
	/**
	 * Returns the instruction at the current address, or a nop if that address has
	 * not been initialized.
	 * @param address of the desired instruction
	 * @return The instruction at address
	 */
	Instruction fetch(int address) {
		if (imem.containsKey(address)) {
			String[] value = imem.get(address);
			byteCount += 4;
			return new Instruction(address, value[0], value[1] );
		} else {
			byteCount += 4;
			return new Instruction(address);
		}
		
	}
	
	/**
	 * Returns the highest key (address) in the instruction memory. 
	 * @return The last address in the instruction memory with an instruction.
	 */
	int getHighestAddress() {
		return imem.lastKey();
	}

}
